package com.umeox.watch.moto.gallery.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.watch.themes.util.UToast;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.dataservice.constants.Constants;
import com.umeox.watch.moto.gallery.R;
import com.umeox.watch.moto.gallery.adapter.PhotoSingleAdapter;
import com.umeox.watch.moto.gallery.ui.widget.ConfirmDialog;
import com.umeox.watch.moto.gallery.utils.NetworkUtils;
import com.umeox.watch.moto.gallery.utils.Util;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

import me.everything.android.ui.overscroll.OverScrollDecoratorHelper;


/**
 * Created by zl on 2017/5/18.
 */

public class SinglePhotoListActivity extends ThemeAppCompatActivity implements PhotoSingleAdapter.OnItemClickListener, View.OnClickListener {

    private static final String TAG = "SinglePhotoListActivity";
    public static final String POSITION = "position";
    public static final String PHOTO_LIST = "photo_list";
    private static final int REQUEST_CODE = 101;
    private final int MSG_DISMISS_VIEW = 0x102;
    private View mOptionView, mBottomOptionView;
    private View mRootView;

    private int mCurrentPosition;
    private ArrayList<String> mPhotos;

    private ArrayList<String> mPhotoList = new ArrayList<>();

    private PhotoSingleAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private PagerSnapHelper mPagerSnapHelper;
    private String mCurrentPhotoPath;

    private RecyclerView photoRv;


    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == MSG_DISMISS_VIEW) {
                mOptionView.setVisibility(View.GONE);
                mBottomOptionView.setVisibility(View.GONE);
                hideSystemUI();
            }
            return false;
        }
    });

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        makeStatusBarTransparent();
        setContentView(R.layout.activity_single_photo_list);

        if (getIntent().hasExtra(POSITION) && getIntent().hasExtra(PHOTO_LIST)) {
            mCurrentPosition = getIntent().getExtras().getInt(POSITION);
            mPhotos = getIntent().getExtras().getStringArrayList(PHOTO_LIST);
            if (mPhotos != null) {
                mCurrentPhotoPath = mPhotos.get(mCurrentPosition);
                mPhotoList.clear();
                mPhotoList.add(mCurrentPhotoPath);
            }
        }
        mRootView = findViewById(R.id.root_view);
        photoRv = findViewById(R.id.rv_photo_preview);
        photoRv.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        photoRv.setLayoutManager(mLayoutManager);
        mAdapter = new PhotoSingleAdapter(mPhotos, this);
        mPagerSnapHelper = new PagerSnapHelper();
        mPagerSnapHelper.attachToRecyclerView(photoRv);
        photoRv.setAdapter(mAdapter);
        // Vertical
        OverScrollDecoratorHelper.setUpOverScroll(photoRv, OverScrollDecoratorHelper.ORIENTATION_HORIZONTAL);

        mOptionView = findViewById(R.id.options_rl);
        mBottomOptionView = findViewById(R.id.options_ll_bottom);

        ImageView ivShare = findViewById(R.id.iv_share);
        ImageView ivUpload = findViewById(R.id.iv_upload);
        ivShare.setOnClickListener(this);
        ivUpload.setOnClickListener(this);

        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.iv_delete).setOnClickListener(this);
        findViewById(R.id.iv_set_wallpaper).setOnClickListener(this);

        photoRv.scrollToPosition(mCurrentPosition);
        final LinearLayoutManager layoutManager = (LinearLayoutManager) photoRv.getLayoutManager();
        if (layoutManager != null) {
            layoutManager.scrollToPositionWithOffset(mCurrentPosition, 0);
        }

        photoRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull @NotNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    /*正在拖拽*/
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        if (mOptionView.getVisibility() == View.VISIBLE) {
                            mOptionView.setVisibility(View.GONE);
                            mBottomOptionView.setVisibility(View.GONE);
                            hideSystemUI();
                        }
                        if (mHandler.hasMessages(MSG_DISMISS_VIEW)) {
                            mHandler.removeMessages(MSG_DISMISS_VIEW);
                        }
                        break;
                    /*滑动停止*/
                    case RecyclerView.SCROLL_STATE_IDLE:
                        resetCurrentItemData();
                        break;
                    /*惯性滑动中*/
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        break;
                }
            }

            @Override
            public void onScrolled(@NonNull @NotNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void resetCurrentItemData() {
        final View view = mPagerSnapHelper.findSnapView(mLayoutManager);
        if (view == null) {
            return;
        }
        mCurrentPosition = mLayoutManager.getPosition(view);
        Logger.e("mCurrentPosition->" + mCurrentPosition);
        mPhotoList.clear();
        mCurrentPhotoPath = mPhotos.get(mCurrentPosition);
        mPhotoList.add(mCurrentPhotoPath);
    }

    @Override
    public void onClick(int position) {
        if (mOptionView.getVisibility() == View.GONE) {
            mOptionView.setVisibility(View.VISIBLE);
            mBottomOptionView.setVisibility(View.VISIBLE);
            mHandler.sendEmptyMessageDelayed(MSG_DISMISS_VIEW, 2000);
            if (mRootView.getSystemUiVisibility() == View.SYSTEM_UI_FLAG_FULLSCREEN) {
                mRootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            }
        } else {
            mOptionView.setVisibility(View.GONE);
            mBottomOptionView.setVisibility(View.GONE);
            hideSystemUI();
            if (mHandler.hasMessages(MSG_DISMISS_VIEW)) {
                mHandler.removeMessages(MSG_DISMISS_VIEW);
            }
        }
    }

    private void hideSystemUI() {
        if (mRootView.getSystemUiVisibility() == View.SYSTEM_UI_FLAG_VISIBLE) {
            mRootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_share:
                if (!DataProvider.isActivated()) {
                    UToast.show(getString(R.string.str_unbond_tip), Toast.LENGTH_LONG);
                    return;
                }
                Uri uri = Uri.parse("chat://file/" + mCurrentPhotoPath);
                Intent intent = new Intent("com.wherecom.intent.action.CHAT", uri);
                startActivity(intent);
                break;
            case R.id.iv_delete:
                showDeleteDialog();
                break;
            case R.id.iv_upload:
                if (!NetworkUtils.isNetworkAvailable(this)) {
                    UToast.showCustomToast(this, R.string.sim_state_unknown, 2000);
                    return;
                }

                if (!DataProvider.isActivated()) {
                    UToast.show(getString(R.string.str_unbond_tip), Toast.LENGTH_LONG);
                    return;
                }
                Intent uploadIntent = new Intent(SinglePhotoListActivity.this, UploadActivity.class);
                uploadIntent.putStringArrayListExtra("list", mPhotoList);
                startActivity(uploadIntent);
                break;
            case R.id.iv_set_wallpaper:
                //show dialog
                ConfirmDialog setWallpaperDialog = new ConfirmDialog(this, getString(R.string.str_set_wallpaper1));
                setWallpaperDialog.setActionClickListener(new ConfirmDialog.ActionClickListener() {
                    @SuppressLint("WrongConstant")
                    @Override
                    public void onConfirm() {
                        Logger.e("mCurrentPhotoPath=" + mCurrentPhotoPath + ",CustomWallpaper=" + DataProvider.getCustomWallpaper());
                        if (TextUtils.isEmpty(DataProvider.getCustomWallpaper()) || !DataProvider.getCustomWallpaper().equals(mCurrentPhotoPath)) {
                            if (DataProvider.setCustomWallpaper(mCurrentPhotoPath)) {
                                Intent wallpaperIntent = new Intent();
                                wallpaperIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | Constants.FLAG_RECEIVER_INCLUDE_BACKGROUND);
                                wallpaperIntent.setAction(Constants.ACTION_REFRESH_WALLPAPERS);
                                sendBroadcast(wallpaperIntent);
                                UToast.show(getResources().getString(R.string.set_wallpaper_success_str), Toast.LENGTH_LONG);
                            }
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
                if (!setWallpaperDialog.isShowing()) {
                    setWallpaperDialog.show();
                }
                break;
        }
    }

    private void showDeleteDialog() {
        ConfirmDialog deleteDialog = new ConfirmDialog(this, getString(R.string.str_delete_item));
        deleteDialog.setActionClickListener(new ConfirmDialog.ActionClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onConfirm() {
                Logger.e(TAG, "mCurrentPosition=" + mCurrentPosition + ",mCurrentPhotoPath:" + mCurrentPhotoPath + "mPhotos.size = " + mPhotos.size());
                Util.deleteImage(SinglePhotoListActivity.this, mCurrentPhotoPath);
                mAdapter.removeItem(mCurrentPosition);
                Logger.e(TAG, "mPhotos.size = " + mPhotos.size());
                if (mCurrentPosition == mPhotos.size()) {
                    mCurrentPosition = mCurrentPosition - 1;
                }
                Logger.e(TAG, "mCurrentPosition = " + mCurrentPosition);
                if (mCurrentPosition >= 0) {
                    mPhotoList.clear();
                    mCurrentPhotoPath = mPhotos.get(mCurrentPosition);
                    mPhotoList.add(mCurrentPhotoPath);
                    photoRv.scrollToPosition(mCurrentPosition);
                }
                if (mPhotos.isEmpty()) {
                    finish();
                }
            }

            @Override
            public void onCancel() {

            }
        });
        if (!deleteDialog.isShowing()) {
            deleteDialog.show();
        }



//        AlertDialog.Builder builder = new AlertDialog.Builder(this)
//                .setMessage(getString(R.string.str_delete_item)).setPositiveButton(getString(R.string.str_ok), (dialogInterface, i) -> {
//                    Logger.e(TAG, "mCurrentPosition=" + mCurrentPosition + ",mCurrentPhotoPath:" + mCurrentPhotoPath + "mPhotos.size = " + mPhotos.size());
//                    Util.deleteImage(SinglePhotoListActivity.this, mCurrentPhotoPath);
//                    mAdapter.removeItem(mCurrentPosition);
//                    Logger.e(TAG, "mPhotos.size = " + mPhotos.size());
//                    if (mCurrentPosition == mPhotos.size()) {
//                        mCurrentPosition = mCurrentPosition - 1;
//                    }
//                    Logger.e(TAG, "mCurrentPosition = " + mCurrentPosition);
//                    if (mCurrentPosition >= 0) {
//                        mPhotoList.clear();
//                        mCurrentPhotoPath = mPhotos.get(mCurrentPosition);
//                        mPhotoList.add(mCurrentPhotoPath);
//                        photoRv.scrollToPosition(mCurrentPosition);
//                    }
//                    if (mPhotos.isEmpty()) {
//                        finish();
//                    }
//                }).setNegativeButton(getString(R.string.str_cancel), (dialogInterface, i) -> dialogInterface.dismiss());
//        AlertDialog deleteDialog = builder.create();
//        deleteDialog.setOnDismissListener(dialog -> getWindow().getDecorView().setSystemUiVisibility(
//                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
//                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY));
//
//        deleteDialog.show();
    }
}
